package com.tywj.lib.core.common.view

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.tywj.lib.core.common.manager.ActivityManager
import com.tywj.lib.core.common.view.interfaces.IInitView

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/8
 *     desc   : 基类Activity
 *     version: 1.0.0
 * </pre>
 */
abstract class BaseActivity : AppCompatActivity(), IInitView {
    // 是否是第一次调用onResume
    private var isFirstOnResume = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (isMainActivity()) {
            ActivityManager.setMainActivity(this)
        } else {
            ActivityManager.addActivity(this)
        }

        val layoutID = getLayoutID()
        if (layoutID == 0) {
            val layoutView = getLayoutView()
            if (layoutView != null) {
                setContentView(layoutView)
            }
        } else {
            setContentView(layoutID)
        }

        initVariable(savedInstanceState)
        initView(savedInstanceState)
        initListener()
        loadDataOnCreate()
    }

    override fun onDestroy() {
        super.onDestroy()

        if (isMainActivity()) {
            ActivityManager.setMainActivity(null)
        } else {
            ActivityManager.removeActivity(this)
        }
    }

    override fun onResume() {
        super.onResume()

        onResumeEveryTime()

        if (isFirstOnResume) {
            isFirstOnResume = false
            onResumeFirst()
        } else {
            onResumeExceptFirst()
        }
    }

    /**
     * 第一次onResume的时候调用
     */
    protected open fun onResumeFirst() {}

    /**
     * 除了第一次onResume都调用
     */
    protected open fun onResumeExceptFirst() {}

    /**
     * 在onResume的时候每次都调用
     */
    protected open fun onResumeEveryTime() {}

    /**
     * 当前Activity是否是MainActivity
     */
    protected open fun isMainActivity(): Boolean = false
}